package com.axones.planningpoker.rest.service;

import org.restlet.data.Status;
import org.restlet.resource.Delete;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;

import com.axones.planningpoker.bean.User;
import com.axones.planningpoker.dao.UserDAO;
import com.google.gson.Gson;

/**
 * Resource which has only one representation.
 * 
 */
public class UserResource extends ServerResource {
	private static UserDAO userDao;
	private static Gson gson;

	public UserResource() {
		if (userDao == null) {
			userDao = new UserDAO();
		}
		if (gson == null) {
			gson = new Gson();
		}
	}
	
	@Post
	public String doCreate(String u) {
		User user = gson.fromJson(u, User.class);		
		
		Long result = userDao.add(user);
	
		if (result != -1) {
			setStatus(Status.SUCCESS_CREATED);
		}
		else 
		{
			setStatus(Status.CLIENT_ERROR_CONFLICT);
		}
		
		return result.toString();
	}

	@Put
	public void doUpdate(String u) {
		User user = gson.fromJson(u, User.class);
		
		String result = userDao.update(user);
		
		if(result == "ok")
		{
			setStatus(Status.SUCCESS_OK);
		} 
		else if(result == "email.used")
		{
			setStatus(Status.CLIENT_ERROR_CONFLICT);
		}
		else if(result == "not.found")
		{
			setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
		}
	}

	@Delete
	public String doDelete() {
		userDao.delete(Long.parseLong((String) getRequest().getAttributes()
				.get("id")));
		return "ok";
	}
}